package com.pjhouse.pipeline.context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public final class LoginContextHolder {

	public static final String ATTR_LOGIN = "login";
	
	public static final String ATTR_LOGIN_LAST = "login_last";

	public static final String ATTR_USER_ID_NUM = "userID";

	public static final String ATTR_USER_NAME = "_name_";
    
	public static final String ATTR_USER_ROLE = "_role_";
	
	public static final ThreadLocal<LoginContext> holder = new ThreadLocal<LoginContext>();
	
	public static LoginContext getLoginContext() {
		LoginContext loginContext = holder.get();
		if(loginContext == null) {
			loginContext = new LoginContext();
			holder.set(loginContext);
		}
		
		return loginContext;
	}

    public static long getUserId() {
        return getLoginContext().getId();
    }

    public static String getUserName() {
        return getLoginContext().getUserName();
    }

    public static boolean isLogin() {
        return getLoginContext() != null && getUserId() > 0;
    }

    public static void setupLoginContext(HttpServletRequest request){
		HttpSession session = request.getSession();
        LoginContext context = LoginContextHolder.getLoginContext();
        
        String userNick = null;
        Long userId = null;
        String role = null;
        Long loginLast = null;
        if(session.getAttribute(ATTR_LOGIN) != null) {
            userId = Long.parseLong((String)CookieUtil.getCookieValue(request, ATTR_USER_ID_NUM));
            userNick = (String)CookieUtil.getCookieValue(request, ATTR_USER_NAME);
            role = (String)CookieUtil.getCookieValue(request, ATTR_USER_ROLE);
            loginLast = Long.parseLong((String)CookieUtil.getCookieValue(request, ATTR_LOGIN_LAST));
        }
        context.setUserName(userNick);
        context.setId(userId == null? 0: userId);
        context.setRole(role);
        context.setLoginLast(loginLast);
	}
	
	public static void clearLoginContext() {
		holder.remove();
	}
}
